<template>
  <view class="approval-history-page">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-left" @click="goBack">
        <u-icon name="arrow-left" color="#ffffff" size="24"></u-icon>
      </view>
      <view class="nav-center">
        <text class="nav-title">我的审批</text>
      </view>
      <view class="nav-right"></view>
    </view>

    <!-- 筛选区域 -->
    <view class="search-card">
      <view class="search-header" @click="toggleSearch">
        <view class="search-header-left">
          <u-icon name="search" size="18" color="#1678ff"></u-icon>
          <text class="search-header-title">筛选条件</text>
        </view>
        <view class="search-header-right">
          <text class="expand-text">{{ searchExpanded ? '收起' : '展开' }}</text>
          <u-icon
            :name="searchExpanded ? 'arrow-up' : 'arrow-down'"
            size="16"
            color="#999"
          ></u-icon>
        </view>
      </view>
      <view v-show="searchExpanded" class="search-form">
        <view class="search-row">
          <view class="form-item">
            <text class="label">申请人</text>
            <u-input
              v-model="searchForm.applicantName"
              placeholder="请输入申请人姓名"
              :clearable="true"
              :custom-style="{ flex: 1 }"
            />
          </view>
        </view>
        <view class="search-row">
          <view class="form-item">
            <text class="label">部门</text>
            <u-input
              v-model="searchForm.departmentName"
              placeholder="请输入申请部门"
              :clearable="true"
              :custom-style="{ flex: 1 }"
            />
          </view>
        </view>
        <view class="search-row">
          <view class="form-item">
            <text class="label">年月</text>
            <view class="date-picker-row">
              <picker
                mode="date"
                fields="month"
                :value="searchForm.yearMonth"
                @change="handleMonthChange"
              >
                <view class="picker-input">
                  <text v-if="searchForm.yearMonth">{{ searchForm.yearMonth }}</text>
                  <text v-else class="placeholder">选择年月</text>
                </view>
              </picker>
              <u-icon
                v-if="searchForm.yearMonth"
                name="close-circle-fill"
                color="#c0c4cc"
                size="18"
                @click.stop="clearYearMonth"
              />
            </view>
          </view>
        </view>
        <view class="search-actions">
          <u-button type="primary" size="small" @click="handleSearch">搜索</u-button>
          <u-button type="info" size="small" plain @click="handleReset">重置</u-button>
        </view>
      </view>
    </view>

    <!-- 列表区域 -->
    <view class="list-card">
      <view v-if="loading" class="loading-box">
        <u-loading-icon size="28" text="加载中..." />
      </view>

      <view v-else>
        <view v-if="list.length" class="approval-list">
          <view v-for="item in list" :key="item.id" class="approval-item" @click="handleView(item)">
            <view class="item-header">
              <view class="title-block">
                <text class="title">{{ item.reason || '请假申请' }}</text>
                <text class="subtitle" v-if="item.location">地点：{{ item.location }}</text>
              </view>
              <view class="header-tags">
                <u-tag
                  :text="getSourceLabel((item as any).isInternal)"
                  :type="(item as any).isInternal === 0 ? 'warning' : 'primary'"
                  size="mini"
                  plain
                  style="margin-right: 12rpx"
                />
                <u-tag
                  :text="getStatusLabel(item.currentStatus || '')"
                  :type="getStatusTagType(item.currentStatus || '')"
                  size="mini"
                  plain
                />
              </view>
            </view>

            <view class="item-body">
              <view class="info-row">
                <text class="info-label">申请人</text>
                <text class="info-value">{{ item.applicantName || '-' }}</text>
              </view>
              <view class="info-row">
                <text class="info-label">{{ getDepartmentLabel((item as any).isInternal) }}</text>
                <text class="info-value">{{ item.departmentName || item.companyName || '-' }}</text>
              </view>
              <view class="info-row">
                <text class="info-label">时段</text>
                <text class="info-value">
                  {{ formatDateRange(item.startTime, item.endTime) }}
                </text>
              </view>
              <!-- <view class="info-row">
                <text class="info-label">天数</text>
                <text class="info-value">{{ item.totalDays ?? '-' }}</text>
              </view> -->
            </view>
          </view>
        </view>
        <u-empty v-else mode="list" text="暂无审批历史" />
      </view>

      <view v-if="pagination.total > pagination.size" class="pagination-wrapper">
        <u-pagination
          v-model="pagination.current"
          :total="pagination.total"
          :page-size="pagination.size"
          @change="handlePageChange"
        />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useMemberStore } from '@/stores/modules/member'
import { getMyLeaveApprovalHistory, type LeaveApplicationDetail } from '@/Api/leave'

const memberStore = useMemberStore()

// 搜索区域折叠状态
const searchExpanded = ref(false)

// 搜索表单
const searchForm = reactive({
  applicantName: '',
  departmentName: '',
  yearMonth: '',
})

// 列表数据
const list = ref<LeaveApplicationDetail[]>([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
})

// 生命周期
onMounted(() => {
  // 初始化操作可以放在这里，但不调用接口
})

onShow(() => {
  // 页面显示时刷新列表（包括首次进入和从其他页面返回）
  loadList()
})

// 方法
const loadList = async () => {
  try {
    loading.value = true
    const userInfo = memberStore.profile
    if (!userInfo?.id) {
      uni.showToast({ title: '用户信息不完整', icon: 'none' })
      return
    }

    // 构建搜索参数
    const params: any = {}
    if (searchForm.applicantName) {
      params.applicantName = searchForm.applicantName
    }
    if (searchForm.departmentName) {
      params.departmentName = searchForm.departmentName
    }
    if (searchForm.yearMonth) {
      const [year, month] = searchForm.yearMonth.split('-')
      params.year = parseInt(year)
      params.month = parseInt(month)
    }

    console.log('📤 发送请求，参数:', {
      approverId: userInfo.id,
      pageNum: pagination.current,
      pageSize: pagination.size,
      searchParams: params,
    })

    const res: any = await getMyLeaveApprovalHistory(
      userInfo.id,
      pagination.current,
      pagination.size,
      params,
    )

    console.log('📥 接收响应:', res)

    const body = res?.data || res
    if (body?.code && body.code !== 200) {
      throw new Error(body.message || '加载失败')
    }
    const data = body?.data || body

    console.log('✅ 解析数据:', {
      records: data?.records?.length || 0,
      total: data?.total || 0,
    })

    list.value = data?.records || []
    pagination.total = data?.total || 0
  } catch (error: any) {
    console.error('❌ 加载审批历史失败:', error)
    uni.showToast({ title: error?.message || '加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  pagination.current = page
  loadList()
}

const handleSearch = () => {
  console.log('🔍 执行搜索，搜索条件:', searchForm)
  pagination.current = 1
  loadList()
}

const handleReset = () => {
  console.log('🔄 重置搜索条件')
  searchForm.applicantName = ''
  searchForm.departmentName = ''
  searchForm.yearMonth = ''
  pagination.current = 1
  loadList()
}

const handleMonthChange = (e: any) => {
  searchForm.yearMonth = e.detail.value
}

const clearYearMonth = () => {
  searchForm.yearMonth = ''
  handleSearch()
}

const toggleSearch = () => {
  searchExpanded.value = !searchExpanded.value
}

// 返回上一页
const goBack = () => {
  const pages = getCurrentPages()
  if (pages.length <= 1) {
    uni.reLaunch({
      url: '/pages/index/index',
    })
  } else {
    uni.navigateBack({
      delta: 1,
    })
  }
}

const handleView = (row: LeaveApplicationDetail) => {
  // 跳转到详情页面（查看模式）
  uni.navigateTo({
    url: `/pages/leave/forms/index?id=${row.id}&templateName=${encodeURIComponent(
      row.flowTemplateName || '请假申请',
    )}&templateCode=${inferTemplateCode(row.flowTemplateName)}&mode=view`,
  })
}

const inferTemplateCode = (name?: string, fallback?: string) => {
  if (fallback) return fallback
  if (!name) return 'leave_report'
  // 内部人员
  if (name.includes('内部')) return 'outing_report'
  // 外部人员
  return 'leave_report'
}
// 工具函数
const getInternalTypeLabel = (row: LeaveApplicationDetail) => {
  return row.leaveTypeName === '外出报备' ? '外出报备' : '请假申请'
}

const getInternalTypeTag = (row: LeaveApplicationDetail) => {
  return row.leaveTypeName === '外出报备' ? 'warning' : 'primary'
}

const getStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    draft: '草稿',
    pending: '审批中',
    approved: '已通过',
    rejected: '已拒绝',
  }
  return statusMap[status] || status
}

const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    draft: 'info',
    pending: 'warning',
    approved: 'success',
    rejected: 'error',
  }
  return typeMap[status] || 'info'
}

const formatDateTime = (value?: string) => {
  if (!value) return '-'
  return value.replace('T', ' ').substring(0, 16)
}

const formatDate = (value?: string) => {
  if (!value) return '-'
  return value.substring(0, 10)
}

const formatDateRange = (start?: string, end?: string) => {
  if (!start || !end) return '-'
  return `${formatDateTime(start)} 至 ${formatDateTime(end)}`
}

// 获取来源标签（根据 isInternal 字段）
// isInternal: 0-内部单位（内部部门），1-外部单位
const getSourceLabel = (isInternal?: number) => {
  // 如果字段未定义，默认为内部部门
  if (isInternal === undefined || isInternal === null) {
    return '内部部门'
  }
  // isInternal = 0 表示内部单位（内部部门）
  // isInternal = 1 表示外部单位
  return isInternal === 0 ? '内部部门' : '外部单位'
}

// 获取部门/单位标签（根据 isInternal 字段）
// isInternal: 0-内部单位（显示"部门"），1-外部单位（显示"单位"）
const getDepartmentLabel = (isInternal?: number) => {
  // 如果字段未定义，默认为"部门"
  if (isInternal === undefined || isInternal === null) {
    return '部门'
  }
  // isInternal = 0 表示内部单位，显示"部门"
  // isInternal = 1 表示外部单位，显示"单位"
  return isInternal === 0 ? '部门' : '单位'
}
</script>

<style scoped lang="scss">
.approval-history-page {
  height: 100vh;
  background: #f5f6fa;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  /* 顶部导航 */
  .nav-header {
    background: #818cf8;
    padding: 46px 32rpx 20rpx 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: white;
    z-index: 99;

    .nav-left {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .nav-center {
      flex: 1;
      text-align: center;

      .nav-title {
        font-size: 36rpx;
        font-weight: bold;
      }
    }

    .nav-right {
      min-width: 22px;
    }
  }

  .search-card {
    background: #fff;
    border-radius: 24rpx;
    padding: 0;
    margin: 24rpx;
    box-shadow: 0 10rpx 30rpx rgba(15, 35, 95, 0.08);
    overflow: hidden;
  }

  .search-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 28rpx;
    cursor: pointer;
    transition: background 0.3s;

    &:active {
      background: #f8f9fa;
    }

    .search-header-left {
      display: flex;
      align-items: center;

      > *:not(:last-child) {
        margin-right: 12rpx;
      }

      .search-header-title {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
      }
    }

    .search-header-right {
      display: flex;
      align-items: center;

      > *:not(:last-child) {
        margin-right: 8rpx;
      }

      .expand-text {
        font-size: 26rpx;
        color: #999;
      }
    }
  }

  .search-form {
    display: flex;
    flex-direction: column;
    padding: 0 28rpx 24rpx;
    border-top: 1rpx solid #f0f0f0;
  }

  .list-card {
    background: #f5f6fa;
    border-radius: 0;
    padding: 0 24rpx 24rpx;
    box-shadow: none;
    flex: 1;
    overflow: auto;
  }

  .loading-box {
    padding: 80rpx 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .search-row {
    display: flex;
    flex-direction: column;

    .form-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 4rpx 0;
      border-bottom: 1rpx solid #f0f2f5;

      &:last-child {
        border-bottom: none;
      }

      .label {
        font-size: 28rpx;
        color: #606266;
        font-weight: 500;
        margin-right: 16rpx;
      }

      .date-picker-row {
        display: flex;
        align-items: center;
        flex: 1;

        > *:not(:last-child) {
          margin-right: 16rpx;
        }

        picker {
          flex: 1;
        }

        .picker-input {
          padding: 24rpx;
          background: #f5f7ff;
          border-radius: 16rpx;
          border: 1rpx solid #dce2ff;
          font-size: 28rpx;
          color: #1f2b5b;

          .placeholder {
            color: #a0a4ab;
          }
        }
      }
    }
  }

  .search-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 12rpx;

    > *:not(:last-child) {
      margin-right: 16rpx;
    }

    :deep(.u-button) {
      min-width: 120rpx;
      height: 64rpx;
      font-size: 26rpx;
      border-radius: 8rpx;

      &:after {
        display: none;
      }
    }
  }

  .approval-list {
    display: flex;
    flex-direction: column;

    .approval-item {
      border: none;
      border-radius: 24rpx;
      padding: 32rpx;
      background: #ffffff;
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
      margin-bottom: 24rpx;
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;

      &:active {
        transform: translateY(-2rpx);
        box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.12);
      }

      .item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 6rpx;
        margin-bottom: 24rpx;
        padding-bottom: 20rpx;
        border-bottom: 1rpx solid #f0f2f5;

        .title-block {
          flex: 1;
          min-width: 0;
          display: flex;
          flex-direction: column;

          > *:not(:last-child) {
            margin-bottom: 6rpx;
          }

          .title {
            font-size: 34rpx;
            color: #1f2a56;
            font-weight: 700;
            line-height: 1.4;
            word-break: break-all;
          }

          .subtitle {
            font-size: 24rpx;
            color: #909399;
            line-height: 1.4;
          }
        }

        .header-tags {
          display: flex;
          align-items: center;
          flex-shrink: 0;
          margin-left: 16rpx;
        }
      }

      .item-body {
        display: flex;
        flex-direction: column;
        margin-bottom: 24rpx;

        > *:not(:last-child) {
          margin-bottom: 16rpx;
        }

        .info-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 28rpx;
          line-height: 1.6;

          .info-label {
            color: #606266;
            font-weight: 500;
            min-width: 140rpx;
          }

          .info-value {
            color: #303133;
            font-weight: 500;
            text-align: right;
            flex: 1;
            word-break: break-all;
          }
        }
      }
    }
  }

  .pagination-wrapper {
    margin-top: 16rpx;
    display: flex;
    justify-content: center;
  }
}
</style>
